package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    private void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner in = new Scanner(System.in);
        while(true){
            // 1. 等待用户进行输入
            System.out.print("-> ");
            if(!in.hasNext()){
                break;
            }
            String request = in.next();
            // 2. 根据用户输入，构造 DatagramPacket 对象
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            // 3. 将构造好的请求发送给服务器
            socket.send(requestPacket);
            // 4. 构造 DatagramPacket 用于接收服务器响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            // 5. 接收服务器返回的响应
            socket.receive(responsePacket);
            // 6. 解析响应，并打印
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
